package net.qunzhi.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qunzhi.common.exception.RRException;
import net.qunzhi.common.utils.BaseQuery;
import net.qunzhi.common.utils.Constant;
import net.qunzhi.common.utils.PageUtils;
import net.qunzhi.common.utils.Query;
import net.qunzhi.modules.app.dao.AppTbAlarmRecordConfirmDao;
import net.qunzhi.modules.app.entity.AppTbAlarmRecordConfirmEntity;
import net.qunzhi.modules.app.query.AlarmRecordQuery;
import net.qunzhi.modules.app.service.AppTbAlarmRecordConfirmService;
import net.qunzhi.modules.cms.entity.TbAlarmRecordEntity;
import org.springframework.stereotype.Service;

import java.util.Optional;


@Service("appTbAlarmRecordConfirmService")
public class AppTbAlarmRecordConfirmServiceImpl extends ServiceImpl<AppTbAlarmRecordConfirmDao, AppTbAlarmRecordConfirmEntity> implements AppTbAlarmRecordConfirmService {

    @Override
    public PageUtils queryPage(AlarmRecordQuery query, long userId) {
        IPage<TbAlarmRecordEntity> page = this.baseMapper.page(
                new Query<AppTbAlarmRecordConfirmEntity>().getPage(query),
                new QueryWrapper<AppTbAlarmRecordConfirmEntity>()
                        .eq("arc.user_id", userId)
                        .eq(null!=query.getIsConfirm(),"arc.is_confirm", query.getIsConfirm())
                        .le(null!=query.getEndDate(),"date(arc.create_time)", query.getEndDate())
                        .ge(null!=query.getStartDate(),"date(arc.create_time)", query.getStartDate())
                        .orderByDesc("ar.create_time")
        );

        return new PageUtils(page);
    }

    @Override
    public void confirm(AppTbAlarmRecordConfirmEntity form, long userId) {
        QueryWrapper<AppTbAlarmRecordConfirmEntity> qw = new QueryWrapper<AppTbAlarmRecordConfirmEntity>()
                .eq("alarm_record_id", form.getAlarmRecordId())
                .eq("user_id", userId);
        Optional.ofNullable(
                this.getOne(qw)
        ).ifPresent(data -> {
            if (Constant.ONE == data.getIsConfirm()) {
                throw new RRException("报警信息已确认");
            }
        });
        form.setUserId(userId).setIsConfirm(Constant.ONE);
        this.update(form, qw);
    }

}